from flask import Blueprint, jsonify
from flask import request, redirect, g
from flask import make_response
from common.libs.Helper import ops_render
from common.libs.Helper import getCurrentDate
from common.libs.user.UserService import UserService
from common.libs.UrlManager import UrlManager
from common.models.log import AppAccessLog
from common.libs.page_utils import Pagination
from common.models.user import User
from application import app
from sqlalchemy import or_
import json

route_account = Blueprint('account_page', __name__)

@route_account.route('/index')
def index():
    """
    使用自定义分页类实现分页
    """
    # query = User.query
    # resp = request.values
    #
    # # 混合搜索
    # if 'mix_kw' in resp:
    #     rule = or_(User.nickname.like('%{}%'.format(resp['mix_kw'])), User.mobile.like('%{}%'.format(resp['mix_kw'])))
    #     query = query.filter(rule)
    #
    # # 搜索状态
    # if 'status' in resp and int(resp['status']) > -1:
    #     query = query.filter(User.status == resp['status'])
    #
    # user_list = query.filter().order_by(User.uid.desc())
    # # current_page(表示当前页)
    # current_page = resp.get('page', default=1)
    # # total_count(表示数据总条数)
    # total_count = query.count()
    # # base_url(表示分页URL前缀)
    # base_url = request.path
    # # params(表示请求传入的数据)
    # params = request.args
    # # per_page_count=10(指定每页显示数)
    # per_page_count = app.config['PAGE_SIZE']
    # # max_pager_count(指定页面最大显示页码,默认11)
    # max_pager_count = app.config['PAGE_DISPLAY']
    # pager_obj = Pagination(current_page, total_count, base_url, params, per_page_count, max_pager_count)
    # user_list = user_list[pager_obj.start:pager_obj.end]
    # html = pager_obj.page_html()
    # return ops_render(
    #     'account/index.html',
    #     {
    #         'user_list': user_list,
    #         'html': html,
    #         'search_val':resp,
    #         'STATUS_LIST':app.config['ACCOUNT_SEARCH_STATUS'],
    #         'total_count':total_count,
    #         'per_page':per_page_count
    #     }
    # )

    # 使用flask的paginate实现快速分类

    query = User.query
    resp = request.values
    resp_data = {}

    # 混合搜索
    if 'mix_kw' in resp:
        rule = or_(
            User.nickname.like('%{}%'.format(resp['mix_kw'])),
            User.mobile.like('%{}%'.format(resp['mix_kw']))
        )
        query = query.filter(rule)

    # 搜索状态
    if 'status' in resp and int(resp['status']) > -1:
        query = query.filter(User.status == resp['status'])

    # 指定当前页码
    page = resp.get('page', type=int)
    page_url = request.full_path.replace('&page={}'.format(page), '')
    # 定义每页显示数
    page_size = app.config['PAGE_SIZE']
    # 创建分页对象
    pagination = query.filter().order_by(User.uid.desc()).paginate(page, page_size, False)

    resp_data['STATUS_LIST'] = app.config['STATUS_MAPPING']
    resp_data['pagination'] = pagination
    resp_data['search_val'] = resp
    resp_data['page_url'] = page_url
    resp_data['placeholder']='请输入姓名或者手机号码'

    return ops_render('account/index.html', resp_data)

@route_account.route('/info')
def info():
    """
    展示用户信息视图函数
    :return:
    """
    resp_data = {}
    uid = request.args.get('id')

    back_url = UrlManager.buildUrl('/account/index')
    if not uid:
        return redirect(back_url)
    user = User.query.filter_by(uid=uid).first()
    if not user:
        # 查无此人，跳转回首页
        return redirect(back_url)

    # 显示前5条的访问记录
    access_list = AppAccessLog.query.filter(AppAccessLog.uid == uid).order_by(AppAccessLog.id.desc()).limit(8)

    resp_data['user'] = user
    resp_data['access_list'] = access_list
    return ops_render('account/info.html', resp_data)

@route_account.route('/set', methods=['GET', 'POST'])
def set():
    """
    该视图函数用于添加账号和修改账号
    :return:
    """
    # 设置默认显示密码
    default_pwd = '********'
    if request.method == 'GET':
        resp_data = {}
        uid = request.args.get('id')
        user = None
        # 存在id则为修改，不存在则表示添加
        if uid:
            user = User.query.filter_by(uid=uid).first()
            # 删除用户不允许修改
            if user.status==0:
                return redirect('/account/index')
            resp_data['default_pwd'] = default_pwd
        resp_data['user'] = user
        return ops_render('account/set.html', resp_data)

    result = {'code': 200, 'data': [], 'msg': '操作成功!'}
    req = request.values
    id = request.form.get('id', type=int, default=0)
    # id = req['id'] if req['id'] else 0
    nickname = req.get('nickname')
    mobile = req.get('mobile')
    email = req.get('email')
    login_name = req.get('login_name')
    login_pwd = req.get('login_pwd')

    # 后端验证登入名，手机号和邮箱
    is_login_name = User.query.filter(User.login_name == login_name, User.uid != id).first()
    if is_login_name:
        result['code'] = -1
        result['msg'] = '该用户名已经存在，请更换！'
        return jsonify(result)

    is_mobile = User.query.filter(User.mobile == mobile, User.uid != id).first()
    if is_mobile:
        result['code'] = -1
        result['msg'] = '该手机号已被注册，请更换！'
        return jsonify(result)

    is_email = User.query.filter(User.email == email, User.uid != id).first()
    if is_email:
        result['code'] = -1
        result['msg'] = '该邮箱号已经被注册，请更换！'
        return jsonify(result)

    user_info = User.query.filter_by(uid=id).first()

    # 修改账号信息
    if user_info:
        user_model = user_info
    # 添加账号信息
    else:
        user_model = User()
        user_model.login_salt = UserService.geneSalt()
        user_model.created_time = getCurrentDate()

    user_model.nickname = nickname
    user_model.mobile = mobile
    user_model.email = email
    user_model.login_name = login_name

    # 操作更新时间
    user_model.updated_time = getCurrentDate()

    # 判断是否修改密码
    if login_pwd != default_pwd:
        user_model.login_pwd = UserService.genePwd(login_pwd, user_model.login_salt)
    # 同步到数据库
    user_model.save()

    # 如果是当前用户修改密码，则更新当前用户的cookie值
    if g.current_user.uid == id:
        current_user = g.current_user
        response = make_response(json.dumps(result))
        response.set_cookie(app.config['AUTH_COOKIE_NAME'], '{}#{}'.format(UserService.geneAuthCode(current_user), id))
        return response

    return jsonify(result)

@route_account.route('/cat_ops', methods=['POST'])
def ops():
    """
    删除，回复操作
    :return:
    """
    result = {'code': 200, 'data': [], 'msg': '操作成功!'}
    id = request.values.get('id', type=int, default=0)
    action = request.values.get('action', type=str, default='')

    if not id:
        result['code'] = -1
        result['msg'] = '请选择要操作的账号！'

    if action not in ['remove', 'recover']:
        result['code'] = -1
        result['msg'] = '操作有误，请重试！'

    user = User.query.get(id)
    if not user:
        result['code'] = -1
        result['msg'] = '指定账号不存在！'

    if action == 'remove':
        user.status = 0

    if action == 'recover':
        user.status = 1

    # 修改更新时间
    user.updated_time = getCurrentDate()
    user.update()
    return jsonify(result)
